package com.my12306.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.my12306.common.constant.CommonConstants;
import com.my12306.common.enums.CodeEnum;
import com.my12306.common.exception.RTExcption;
import com.my12306.common.model.vo.PageVo;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.RedisUtils;
import com.my12306.common.util.SnowflakeIdWorker;
import com.my12306.common.util.response.ResponseData;
import com.my12306.user.dao.PUserDao;
import com.my12306.user.model.po.PUserEntity;
import com.my12306.user.model.po.auth.UserRoleEntity;
import com.my12306.user.model.vo.UserVo;
import com.my12306.user.service.PUserService;
import com.my12306.user.service.auth.RoleService;
import com.my12306.user.service.auth.UserRoleService;
import com.my12306.user.util.auth.UserConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.my12306.common.util.CommentUtils.getPoToVo;
@Slf4j
@Service("pUserService")
public class PUserServiceImpl extends ServiceImpl<PUserDao, PUserEntity> implements PUserService {
    private final static String uk = "user_";
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserRoleService userRoleService;
    @Resource
    private Producer producer;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RoleService roleService;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RTExcption("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        String key = RedisUtils.getKeyPrefix(UserConstant.Prefix, uk, uuid);
        redisUtils.set(key, code, 5, TimeUnit.MINUTES);
        return producer.createImage(code);
    }

    @Override
    public PUserEntity queryUserByUsername(String userNaem) {
        if (userNaem != null) {
            return this.getUserInfoByUsername(userNaem);
        }
        return null;
    }

    @Override
    public PUserEntity queryUserById(Long id) {
        if (id != null) {
            return this.baseMapper.queryUserById(id, CommonConstants.LogicDelete.no_delet.getValue());
        }
        return null;
    }


    @Override
    @Transactional
    public Boolean updateUserById(PUserEntity userEntity) {
        if (userEntity.getPassword() != null) {
            userEntity.setPassword(bCryptPasswordEncoder.encode(userEntity.getPassword()));
        }
        return this.baseMapper.updateById(userEntity) > 0;
    }

    @Override
    public Long saveUser(PUserEntity userEntity) {
        log.error(userEntity.toString());
        if (userEntity != null && userEntity.getUsername() != null && userEntity.getPassword() != null) {
            userEntity.setPassword(bCryptPasswordEncoder.encode(userEntity.getPassword()));
            userEntity.setCreateDate(new Date());
            userEntity.setUpdateDate(new Date());
            userEntity.setId(SnowflakeIdWorker.generateId());
            this.baseMapper.insert(userEntity);
            System.out.println(userEntity);
            return userEntity.getId();
        }
        System.out.println("没进去");
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData saveUserVo(UserVo userVo) {
        List<Long> roleIdList = userVo.getRoleIdList();
        PUserEntity userEntity = new PUserEntity();
        getPoToVo(userVo, userEntity);
        userEntity.setCreateDate(new Date());
        userEntity.setUpdateDate(new Date());
        Long id = saveUser(userEntity);
        System.out.println(id);
        if (id != null) {
            List<UserRoleEntity> userRole = userRoleService.createUserRole(roleIdList, id);
            if (userRoleService.saveRoleUser(userRole)) {
                return ResponseData.ok();
            }
        }
        return ResponseData.fail(CodeEnum.ADD_FAIL.getCode(), CodeEnum.ADD_FAIL.getMessage());
    }

    @Override
    public PUserEntity getUserInfoByUsername(String userName) {
        if (userName != null) {
            return this.baseMapper.queryUserByUserName(userName, CommonConstants.LogicDelete.no_delet.getValue());
        }
        return null;
    }

    @Override
    @Transactional
    public ResponseData deleteBatchByUserIds(List<Long> ids) {
        //删除用户
        this.baseMapper.deleteBatchIds(ids);
        //删除用户和角色的关系
        userRoleService.deleteUserRoleByUserIds(ids);
        return ResponseData.ok();
    }

    @Override
    public Boolean updateUserPasswordById(UserVo userVo) {
        PUserEntity pUserEntity = this.queryUserById(userVo.getId());
        Boolean flag = false;
        boolean matches = bCryptPasswordEncoder.matches(userVo.getPassword(), pUserEntity.getPassword());
        if (matches) {
            pUserEntity = new PUserEntity();
            pUserEntity.setPassword(userVo.getNewPassword());
            pUserEntity.setId(userVo.getId());
            flag = updateUserById(pUserEntity);
        }
        return flag;
    }

    @Override
    public PageUtils queryUserListPage(PageVo pageVo) {
        pageVo.init();
        List<PUserEntity> pUserEntities = this.baseMapper.queryUserListPage(pageVo);
        String likeName = pageVo.getLikeName();
        Integer userCount = querryUserCount(null, likeName);
        PageUtils pageUtils = new PageUtils(userCount, pageVo, pUserEntities);
        return pageUtils;
    }

    @Override
    public Integer querryUserCount(Integer logicDelete, String linkeName) {
        QueryWrapper<PUserEntity> wrapper = new QueryWrapper<>();
        if (linkeName != null) {
            wrapper.like("username", linkeName).or().like("user_desc", linkeName);
        }
        if (logicDelete != null) {
            wrapper.eq("logic_delete", logicDelete);
        }
        return this.baseMapper.selectCount(wrapper);
    }

    @Override
    @Transactional
    public Long registerUser(PUserEntity pUserEntity) {
        log.error("进来了");
        pUserEntity.setCreateDate(new Date());
        pUserEntity.setUpdateDate(new Date());
        //添加用户
        pUserEntity.setImgUrl(UserConstant.imgUrl);
        Long id = saveUser(pUserEntity);
        log.info("id"+id);
        if (id != null) {
            //添加角色
            Long roleId = roleService.queryRoleIdByRoleName(UserConstant.user_role);
            List<UserRoleEntity> userRole = userRoleService.createUserRole(Collections.singletonList(roleId), id);
            if (userRoleService.saveRoleUser(userRole)) {

                return id;
            } else {
                return null;
            }
        }
        return id;
    }

    @Override
    public PUserEntity queryUserByPhone(String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            return this.baseMapper.selectOne(new QueryWrapper<PUserEntity>().eq("phone", phone));
        }
        return null;
    }

    @Override
    public Boolean isMobile(String mobile) {
        if (mobile!=null){
            QueryWrapper<PUserEntity> qw = new QueryWrapper<>();
            qw.eq("phone",mobile);
          return   this.baseMapper.selectOne(qw)==null;
        }
        return false;
    }

}
